package xyz.lilei23.framework.utils;

import xyz.lilei23.framework.bean.GenericBeanDefinition;

import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author jack
 * @date 31/07/2021 16:20
 * @version 1.0
 **/
public class ClassHelper {

    /** The CGLIB class separator: {@code "$$"}. */
    public static final String CGLIB_CLASS_SEPARATOR = "$$";

    public static List<GenericBeanDefinition.Arg> getConstructorArg(Class<?> bdClass) {
        Constructor<?>[] constructors = bdClass.getConstructors();
        if (constructors.length == 0){
            return new ArrayList<>(0);
        }
        Constructor<?> constructor = constructors[0];
        if (constructor.getParameterCount() == 0) {
            return new ArrayList<>(0);
        }
        return Arrays.stream(constructor.getParameterTypes()).map(parameter -> {
            GenericBeanDefinition.Arg arg = new GenericBeanDefinition.Arg();
            arg.setType(parameter);
            arg.setArg(getClassName(parameter.getName()));
            arg.setRef(!parameter.isPrimitive());
            return arg;
        }).collect(Collectors.toList());
    }

    public static String getClassName(String classPath){
        return classPath.substring(classPath.lastIndexOf(".")+1, classPath.lastIndexOf(".") + 2).toLowerCase() + classPath.substring(classPath.lastIndexOf(".") + 2);
    }

    public static boolean isCglibProxyClassName(String className) {
        return (className != null && className.contains(CGLIB_CLASS_SEPARATOR));
    }

}
